package com.pd.modules.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;

import com.pd.modules.common.Settings;
import com.pd.modules.common.logging.LogSingleton;

public class WaitForTCPClients extends Thread
{
	private boolean mContinueListening = true;
	private ServerSocket mListenSocket = null;

	public void stopListening()
	{
		mContinueListening = false;
		try
		{
			if (null != mListenSocket)
				mListenSocket.close();
		} catch (IOException e)
		{
		}
	}

	/**
	 * 
	 * @return
	 */
	public void run()
	{

		try
		{
			mListenSocket = new ServerSocket(Settings.UNICAST_PORT);

			LogSingleton.LOGGER.log(Level.INFO, "Server is now listening for TCP connections");

			// Loop de escuta
			while (mContinueListening)
			{
				Socket clientSocket = mListenSocket.accept();

				LogSingleton.LOGGER.log(Level.INFO, "Client accepted on TCP socket!");

				Thread newClientThread = new Thread(Server.getInstance().getClientThreadsGroup(), new ClientHandler(clientSocket));
				newClientThread.setDaemon(true);
				newClientThread.start();
			}

		} catch (IOException e)
		{
			if( mContinueListening ){
				e.printStackTrace();
				return;
			}
				
			LogSingleton.LOGGER.log(Level.INFO, "Server stopped listening for TCP connections");
		}
	}

}